package edu.jinghuan.lms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.jinghuan.lms.entity.Book;
import edu.jinghuan.lms.mapper.BookMapper;
import edu.jinghuan.lms.service.IBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    
    @Override
    @Transactional
    public boolean save(Book book) {
        book.setAvailableCount(book.getTotalCount());
        return super.save(book);
    }

    @Override
    @Transactional
    public boolean updateById(Book book) {
        Book oldBook = getById(book.getId());
        if (oldBook == null) {
            return false;
        }
        // 如果修改了总数量，同时更新可借数量
        if (book.getTotalCount() != null && !book.getTotalCount().equals(oldBook.getTotalCount())) {
            int diff = book.getTotalCount() - oldBook.getTotalCount();
            book.setAvailableCount(oldBook.getAvailableCount() + diff);
        }
        return super.updateById(book);
    }

    @Transactional
    public boolean updateStock(Long id, Integer stock) {
        Book book = getById(id);
        if (book == null) {
            return false;
        }
        book.setAvailableCount(stock);
        return updateById(book);
    }
}
